<?php
require_once 'ActionsController.php';
class ActionPollsController extends ActionsController {
    
    public $uses = array('Action', 'ActionPoll', 'ActionPollsUsersChoice', 'ActionPollsChoice','Place');
    
    public $layout = 'group';
    
    public function beforeRender() {
        parent::beforeRender();
        
        $group = $this->getCurrentUserGroup();
        $this->set('data2', $group);
    }
    
    public function home(){
        
        $pollsReady = $this->ActionPoll->find('all', array(
            'conditions' => array(
                'Action.groups_id' => $this->getCurrentUserGroupId(),
                'ActionPoll.status' => 'ready' 
            )
        ));
        $pollsEdit = $this->ActionPoll->find('all', array(
            'conditions' => array(
                'Action.groups_id' => $this->getCurrentUserGroupId(),
                'ActionPoll.status' => 'edit' 
            )
        ));
        
        $this->set('polls', $pollsReady);
        $this->set('pollsEdit', $pollsEdit);
        
        
    }
    
    public function add(){
        if (!empty($this->request->data['ActionPoll'])){
            $data = $this->request->data['ActionPoll'];
            $propagation = $data['propagation'];
            
            $response = $this->addAction($propagation);
            $id = $response['Action']['id'];
            $data['actions_id'] = $id;
            $data['status'] = 'edit';            
            $data['nb_pers_current'] = 0;
            $group = $this->getCurrentUserGroup();
            $this->getNbPers($group,'group');
            $data['nb_pers_total'] = ($this->getNbPers($group,'group'))/2;
            $data['lastChangeStatus']= date('c');
            
            if ($this->ActionPoll->save($data)){
                $this->Session->setFlash('Le sondage a été créé. Ajoutez maintenant des questions');
                $this->redirect(array('action' => 'addQuestions'));
            } 
        }
    }
    
    public function setReadyStatus($id){
        /**
         * Vérification que tout les question on des réponses 
         */
        
        
        
        if($this->checkQuestions($id)){
            $this->changeStatus($id, 'ready');
            $this->redirect(array('controller' => 'actionPolls', 'action' => 'home'));
        }
        else{
            $this->Session->setFlash('Action impossible : les questions du sondage doivent avoir au moins 2 réponses.');
            $this->redirect(array('controller' => 'actionPolls', 'action' => 'home'));
        }
    }
    
    public function addQuestions(){        
        if (!empty($this->request->data['ActionQuestion'])){
            $data = $this->request->data['ActionQuestion'];
            
            if ($this->ActionQuestion->save($data)){
                $this->Session->setFlash('Le question a été créé, Ajouter maintenant des réponses');
            }
        }
        
        $data = $this->ActionPoll->find('all', array(
            'conditions' => array(
                'Action.groups_id' => $this->getCurrentUserGroupId(),
                'ActionPoll.status' => 'edit' 
            )
        ));
        
        $this->set('dataPoll', $data);
    }
    
    public function view($id){
        $actionPoll = $this->ActionPoll->find('first', array(
            'conditions' => array(
                'ActionPoll.actions_id' => $id
            )
        ));
        $this->set('hasVoted', $this->hasVoted($id));
        $this->set('actionPoll',$actionPoll);
        
        
        // Nombre total de vote pour la sondage : 
        // revient a regarder le nombre de vote pour une question
        
        $questions = $actionPoll['ActionPollsQuestion'];
        // Pour chaque question :
        foreach ($questions as $key => $question){
            $nbTotalChoices = 0;
            //  calcul du nombre de choix pour chaque réponse
            $questionId = $question['id'];
            
            $choices = $this->ActionPollsChoice->find('list',array(
                'conditions' => array(
                    'ActionPollsChoice.questions_id' => $questionId
                ),
                'recursive' => -1,
            ));
            
            
            $data = $this->ActionPollsUsersChoice->find('all', array(
                'fields' => array(
                    'ActionPollsUsersChoice.choices_id AS id', 'COUNT(ActionPollsUsersChoice.users_id) AS nbVote'
                ),
                'conditions' => array(
                    'ActionPollsUsersChoice.questions_id' => $questionId
                ),
                'group' => array(
                    'ActionPollsUsersChoice.choices_id'
                )        
            ));
            
            $results = array();
             foreach ($data as $key3 => $value){   
                 $results[$value['ActionPollsUsersChoice']['id']] = $value[0]['nbVote'];
            }
            
            foreach ($choices as $key2 => $value){
                $nbTotalChoices +=  isset($results[$key2]) ? $results[$key2] : 0;
            }
            
                
            foreach ($choices as $key2 => $value){

                $nbVote = isset($results[$key2]) ? $results[$key2] : 0;
                $choices[$key2] = array(
                    'name' => $value,
                    'nbVote' => $nbVote,
                    'percent' => ($nbTotalChoices >= 1 ? ($nbVote/$nbTotalChoices) * 100 : 0)
                );
            }

            $questions[$key]['choices'] = $choices;
        }
        
         $this->set('nbTotalChoices', $nbTotalChoices);
         $this->set('questions', $questions);
    }
    
    public function checkQuestions($id){
        $actionPoll = $this->ActionPoll->find('first', array(
            'conditions' => array(
                'ActionPoll.actions_id' => $id
            ),
        ));
        
        $questions = $actionPoll['ActionPollsQuestion'];
        
        if (count($questions) == 0){
            return false;
        }
        // Pour chaque question :
        foreach ($questions as $key => $question){
            $nbTotalChoices = 0;
            $questionId = $question['id'];
            
            $choices = $this->ActionPollsChoice->find('list',array(
                'conditions' => array(
                    'ActionPollsChoice.questions_id' => $questionId
                ),
                'recursive' => -1,
            ));
            
            if (count($choices) < 2){
                return false;
            }
        }
        return true;
    }
    
    public function answer($id){
        
        if (!empty($this->request->data)){
            $data = $this->request->data;
            
            if ($this->addUserChoice($data['ActionPollsQuestion'])){
                
                $idPoll = $id;

                $poll = $this->ActionPoll->find('first', array(
                    'conditions' => array(
                        'ActionPoll.actions_id' => $idPoll
                    )
                ));

                $poll = $this->ActionPoll->save(array(
                    'actions_id'=> $idPoll,        
                    'nb_pers_current' => $poll['ActionPoll']['nb_pers_current'] + 1
                ));


                // Une fois le sondage mis à jour
                if ($poll['ActionPoll']['nb_pers_current'] == $poll['ActionPoll']['nb_pers_total']){

                    $this->propage($poll['Action']['id']);
                }
                
                $this->Session->setFlash("Votre réponse à été enregistré");
                $this->redirect(array('action' => 'view', $id));
            }
            else{
                $this->Session->setFlash("Une erreure est survenue, votre réponse n'a pas pu être enregistré.");                
            }
        }
        
        
        $actionPoll = $this->ActionPoll->find('first', array(
            'conditions' => array(
                'ActionPoll.actions_id' => $id
            )
        ));
        
        
        $max = count($actionPoll['ActionPollsQuestion']);
        for($i =  0; $i < $max; $i++) {
            $actionPoll['ActionPollsQuestion'][$i]['ActionPollsChoice'] = $this->ActionPoll->ActionPollsQuestion->ActionPollsChoice->find('list', array(
                'conditions' => array(
                    'ActionPollsChoice.questions_id' => $actionPoll['ActionPollsQuestion'][$i]['id']
                ),
                'recursive' => -1,
                
            ));
        }
        
        
        $this->set('actionPoll',$actionPoll);
    }
    
    
    
    
    
    
    public function changeStatus($id, $status){
        $data = array(
            'ActionPoll' => array(
                'status' => $status,
                'actions_id' => $id
            )
        );
        return $this->ActionPoll->save($data);
        
    }
    
    
    public function hasVoted($idPoll){
        // TODO : test si l'utilisateur a déja voté 
        $data = $this->ActionPoll->ActionPollsQuestion->ActionPollsUsersChoice->find('first', array(
            'conditions' => array(
                'ActionPollsQuestion.action_polls_id' => $idPoll,
                'ActionPollsUsersChoice.users_id' => $this->getCurrentUserId()
            )
        ));
        
        return !empty($data);
    }


    public function addUserChoice($choices){
        
        foreach ($choices as $questionId => $choiceId){
            $this ->ActionPollsUsersChoice->id = null;
            $d = array();
            
            $d['users_id'] = $this->getCurrentUserId();
            $d['choices_id'] = $choiceId;
            $d['questions_id'] = $questionId ;
            
            $this->ActionPollsUsersChoice->save($d);
        }
        
        
        return true;
    }
    
    
    
    public function propage($idAction) {
        
        $action = $this->Action->find('first', array(
            'conditions' => array(
                'Action.id' => $idAction
            )
        ));
        $group = $this->getCurrentUserGroup();
        
        if ($action['Action']['propagationCurrent'] < $action['Action']['propagationMax']){
            
            if ($action['Action']['propagationCurrent'] == 'group'){
                $propa = 'city';
            }
            else if ($action['Action']['propagationCurrent'] == 'city'){
                $propa = 'department';
            }
            else if ($action['Action']['propagationCurrent'] == 'department'){
                $propa = 'state';
            }
            else if ($action['Action']['propagationCurrent'] == 'state'){
                $propa = 'country';
            }
            else if ($action['Action']['propagationCurrent'] == 'country'){
                $propa = 'world';
            }
            
            $nb_pers_total = $this->getNbPers($mongroup,$propa);
            
            $action['ActionPoll']['nb_pers_total'] = $nb_pers_total;
            $action['Action']['propagationCurrent'] = $propa;
            $action['Action']['places_id'] = getPlacesIdMax($group,$propa);
            
            $action = $this->ActionPoll->save('first', array(
                'conditions' => array(
                    'Action.id' => $idAction
            )
        ));
        }
    }
    
}
?>
